﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.ViewModel.Record.SkipOperationsVMs;
using TyMES.Model.Record;
using TyMES.Communication.Request;
using TyMES.Communication;


namespace TyMES.Controllers
{
    [Area("Record")]
    [AuthorizeJwtWithCookie]
    [ActionDescription("跳站记录")]
    [ApiController]
    [Route("api/SkipOperations")]
	public partial class SkipOperationsController : BaseApiController
    {
        [ActionDescription("Sys.Search")]
        [HttpPost("Search")]
		public IActionResult Search(SkipOperationsSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<SkipOperationsListVM>(passInit: true);
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public SkipOperationsVM Get(string id)
        {
            var vm = Wtm.CreateVM<SkipOperationsVM>(id);
            return vm;
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("Add")]
        public IActionResult Add(SkipOperationsVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("Edit")]
        public IActionResult Edit(SkipOperationsVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                vm.DoEdit(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<SkipOperationsBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }


        [ActionDescription("Sys.Export")]
        [HttpPost("ExportExcel")]
        public IActionResult ExportExcel(SkipOperationsSearcher searcher)
        {
            var vm = Wtm.CreateVM<SkipOperationsListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("ExportExcelByIds")]
        public IActionResult ExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<SkipOperationsListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<SkipOperationsImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(SkipOperationsImportVM vm)
        {
            if (vm!=null && (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData()))
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm?.EntityList?.Count ?? 0);
            }
        }

        [ActionDescription("模板保存")]
        [HttpPost("SaveModel")]
        public ActionResult SaveModel(SaveModelRequest request)
        {
            try
            {
                string ModelName = "Model" + request.stationCode + DateTime.Now.ToString("yyyyMMddHHmmss");
                List<SkipOperations> SkipOperations = new List<SkipOperations>();
                foreach (var skipOperation in request.skipOperations)
                {
                    SkipOperations op = new SkipOperations();

                    op.IsSkip = skipOperation.IsSkip;
                    op.OperationCode = skipOperation.OperationCode;
                    op.RouteVersion = "Model";
                    op.OperationName = skipOperation.OperationName;
                    op.Snnumber = ModelName;
                    SkipOperations.Add(op);
                }
                DC.Set<SkipOperations>().AddRange(SkipOperations);
                DC.SaveChanges();
                return Ok(new ResponseBase(true,"模板保存成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [ActionDescription("模板类型输出")]
        [HttpGet("OutSkipModelType")]
        public ActionResult OutSkipModelType()
        {
            try
            {
                var modeltype = DC.Set<SkipOperations>().Where(x=>x.RouteVersion=="Model").OrderByDescending(x=>x.ID).Select(x=>x.Snnumber).Distinct().ToList();
                return Ok(modeltype);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [ActionDescription("模板数据展示")]
        [HttpPost("ShowSkipModel")]
        public ActionResult ShowSkipModel(ShowSkipModelRequest request)
        {
            try
            {
                var skipModel = DC.Set<SkipOperations>().Where(x => x.Snnumber == request.modelType).OrderBy(x => x.OperationCode).ToList();
                return Ok(skipModel);
            }
            catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [ActionDescription("执行模板跳站")]
        [HttpPost("ExecuteSkipByModel")]
        public ActionResult ExecuteSkipByModel(ExecuteSkipByModelRequest request)
        {
            try
            {
                var judgerepeat = DC.Set<SkipOperations>().Where(x => x.Snnumber == request.Snnumber).ToList();
                if(judgerepeat.Count!=0)
                    return Ok(new ResponseBase(false, "已完成"+request.Snnumber+"的跳站选择"));
                List<SkipOperations> skipOperations = new List<SkipOperations>();
                foreach(var op in request.skipOperations)
                {
                    SkipOperations skip = new SkipOperations();
                    skip.Snnumber = request.Snnumber;
                    skip.OperationCode = op.OperationCode;
                    skip.OperationName = op.OperationName;
                    skip.IsSkip = op.IsSkip;
                    skip.AddTime = DateTime.Now;
                    skipOperations.Add(skip);
                }
                DC.Set<SkipOperations>().AddRange(skipOperations);
                DC.SaveChanges();
                return Ok(new ResponseBase(true, request.Snnumber+"跳站选择保存成功"));
            }
            catch(Exception ex)
            {
                return BadRequest(new ResponseBase(false, "跳站选择保存异常："+ex.Message));
            }
        }

        [ActionDescription("执行自定义跳站")]
        [HttpPost("ExecuteSkipByCustom")]
        public ActionResult ExecuteSkipByCustom(ExecuteSkipByCustomRequest request)
        {
            try
            {
                var judgerepeat = DC.Set<SkipOperations>().Where(x => x.Snnumber == request.Snnumber).ToList();
                if (judgerepeat.Count != 0)
                    return Ok(new ResponseBase(false, "已完成" + request.Snnumber + "的跳站选择"));
                List<SkipOperations> skipOperations = new List<SkipOperations>();
                foreach (var op in request.skipOperations)
                {
                    SkipOperations skip = new SkipOperations();
                    skip.Snnumber = request.Snnumber;
                    skip.OperationCode = op.OperationCode;
                    skip.OperationName = op.OperationName;
                    skip.IsSkip = op.IsSkip;
                    skip.AddTime = DateTime.Now;
                    skipOperations.Add(skip);
                }
                DC.Set<SkipOperations>().AddRange(skipOperations);
                DC.SaveChanges();
                return Ok(new ResponseBase(true, request.Snnumber+"跳站选择保存成功"));
            }
            catch(Exception ex)
            {
                return BadRequest(new ResponseBase(false, "跳站选择保存异常：" + ex.Message));
            }
        }

    }
}
